package com.qipay.auth.service.impl;

import com.qipay.auth.service.AuthService;
import com.qipay.baas.model.Cp;
import com.qipay.mapper.CpMapper;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.service.JWTTokenService;
import com.qipay.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    CpMapper cpMapper;

    @Autowired
    JWTTokenService jwtTokenService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public String getToken(String appId, String secretId) {
        Cp current = cpMapper.selectByAppId(appId);
        Assert.notNull(current, "找不到该商户");
        Assert.isTrue(StringUtils.equals(current.getSecretId(), secretId),
                ResultUtils.buildErrorMsg(ApiStatusEnum.ARGUMENT_ERR,"密钥或AppId错误"));

        final UserDetails userDetails = userDetailsService.loadUserByUsername(current.getAppId());
        final String token = jwtTokenService.generateToken(userDetails);

        return token;
    }

    @Override
    public String refreshToken(String token) {
        String appId = jwtTokenService.getUsernameFromToken(token);
        return jwtTokenService.refreshToken(token);
    }
}
